export class WebClient {
    hostname = '47.108.233.67'
    port = 8007
    timeout = 5
    keepAlive = 5
    cleanSession = true
    ssl = false
    password = 'user123456'
    chattocpic = "/root/one2one/chat/cus_9"
    clientId = ''
    userName = ''
    client = null
    path = ''

    constructor(clientID, clientObj, path) {
        this.clientId = clientID
        this.userName = clientID
        this.client = clientObj
        this.path = path
    }

    // this.client.onMessageArrived  = this.receive;
    options = {
        invocationContext: {
            host: this.hostname,
            port: this.port,
            path: this.path,
            clientId: this.clientId
        },
        timeout: this.timeout,
        keepAliveInterval: this.keepAlive,
        cleanSession: this.cleanSession,
        useSSL: this.ssl,
        userName: this.userName,
        password: this.password,
        onSuccess: this.onSuccessFunc,

    };


    onSuccessFunc() {
        console.log("onConnected");
        window.clientNum +=1
        console.log("client链接数量"+ window.clientNum)
    }

    connect() {
        //赋值
        this.options.invocationContext.path = this.path
        this.options.invocationContext.clientId = this.clientId
        this.options.userName = this.userName
        this.options.invocationContext.path = this.path
        this.options.invocationContext.clientId = this.clientId

        this.client.onConnectionLost = function (e) {
            this.client.connect(options);
            console.log(e);
        }
        this.client.connect(this.options);
        this.client.onMessageArrived = this.receive;
    }

    send(messageObj) {
        messageObj.destinationName = this.chattocpic;
        this.client.send(messageObj);
    }

    receive(message) {
        // console.log(JSON.stringify(message));
        // console.log("reciv:" + message.destinationName);
        // console.log("reciv:" + message.payloadString);
        // console.log("qos->" + message.qos)
        // return message.payloadString;
        /**
         *
         * 添加协议解析
         *
         */
        let getMessage = {userName: 'agent', msg: skilHeadContent(message.payloadBytes)}

        // console.log(this.clientId+"->reciv:"+getMessage.msg);
        //首先判断内存是否已经存在该clientId值,存在则更新，不存在则插入
        let localMsg = window.localStorage.getItem(this.clientId)
        let array = []
        // if (localMsg != null && localMsg != '') {
        //     //如果原来有数据先清理在保存
        //     let newArray = JSON.parse(localMsg)
        //     newArray.push(localMsg)
        //     window.localStorage.setItem(this.clientId, JSON.stringify(newArray))
        // } else {
        array.push(getMessage)
        window.localStorage.setItem(this.clientId, JSON.stringify(array));
        // }
    }
}

/**
 * 大端-字节转化成int
 * @param bytes
 * @param off
 * @returns {number}
 */
function bytesToInt2(bytes, off) {
    var b3 = bytes[off] & 0xFF;
    var b2 = bytes[off + 1] & 0xFF;
    var b1 = bytes[off + 2] & 0xFF;
    var b0 = bytes[off + 3] & 0xFF;
    return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0;
}

/**
 * 直接跳过报文头部
 * @param bytes
 * @returns {string|string}
 */
function skilHeadContent(bytes){

    var len=bytesToInt2(bytes,0);
    var len2=bytesToInt2(bytes,4+len);


    var content= byteToString(bytes,4+len+4+len2+4);

    return content;

}

/**
 * 字节转化成字符串
 * @param arr
 * @param offset
 * @returns {string}
 */
function byteToString(arr,offset) {
    if (typeof arr === 'string') {
        return arr;
    }
    var str = '',
        _arr = arr;
    for (var i = offset; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
            v = one.match(/^1+?(?=0)/);
        if (v && one.length == 8) {
            var bytesLength = v[0].length;
            var store = _arr[i].toString(2).slice(7 - bytesLength);
            for (var st = 1; st < bytesLength; st++) {
                store += _arr[st + i].toString(2).slice(2);
            }
            str += String.fromCharCode(parseInt(store, 2));
            i += bytesLength - 1;
        } else {
            str += String.fromCharCode(_arr[i]);
        }
    }
    return str;
}
